use crate::api::ResponseBean;
use actix_web::{
    error, 
    http::{header::ContentType, StatusCode},
    HttpResponse,
};

use derive_more::Display;
use rbdc;
use std::io; 
use thiserror::Error;

#[derive(Debug, Display, Error)]
pub enum MyError {  
    #[display(fmt = "io err")]
    Io(#[from] io::Error),

    #[display(fmt = "db err")]
    Db(#[from] rbdc::Error), 

    #[display(fmt = "系统忙，请稍后在试！")]
    Other(#[from] anyhow::Error),  
}

impl error::ResponseError for MyError {
    fn error_response(&self) -> HttpResponse {
        // 打印错误信息，由于输出给用户的错误信息被处理过，无法显示真实有效的错误内容。这里则把真实错误打印出来。
        match self.clone() {
            MyError::Io(e) => log::error!("{}", e),
            MyError::Db(e) => log::error!("{}", e),
            MyError::Other(e) => log::error!("{}", e),
            _ => (),
        };

        HttpResponse::build(self.status_code())
            .insert_header(ContentType::json())
            .json(ResponseBean {
                code: -1,
                msg: self.to_string(),
                bundle: None,
            })
    }

    fn status_code(&self) -> StatusCode {
        match *self {
            _ => StatusCode::OK, // 所有错误均返回 200 http 状态码？ 错误具体代码使用 json 的code返回
        }
    }
}
